package com.xy.work.template.base.config;
import com.mongodb.client.MongoClients;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;
/**
 * @author 牛牛
 */
@Slf4j
@Configuration
public class MongoConfig {
    /**
     * 设置 master MongoDB 配置
     * @return
     */
    @Primary
    @Bean(name = "masterMongoProperties")
    @ConfigurationProperties(prefix="spring.data.mongodb.master")
    public MongoProperties masterMongoProperties(){
        return new MongoProperties();
    }
    /**
     * 设置 slave MongoDB 配置
     * @return
     */
    @Bean(name = "slaveMongoProperties")
    @ConfigurationProperties(prefix="spring.data.mongodb.slave")
    public MongoProperties slaveMongoProperties(){
        return new MongoProperties();
    }
    /**
     * master 数据库
     * @return
     */
    @Primary
    @Bean(value = "masterMongoTemplate")
    public MongoTemplate getMasterMongoTemplate() {
        MongoProperties masterMongoProperties=masterMongoProperties();
        log.info("masterMongoTemplate：{}", masterMongoProperties.getUri());
        return new MongoTemplate(new SimpleMongoClientDatabaseFactory(
                        MongoClients.create(masterMongoProperties.getUri()),
                        masterMongoProperties.getMongoClientDatabase()
                ));
    }
    /**
     * slave 数据库
     * @return
     */
    @Bean(value = "slaveMongoTemplate")
    public MongoTemplate getSlaveMongoTemplate() {
        MongoProperties slaveMongoProperties=slaveMongoProperties();
        log.info("slaveMongoTemplateUrl：{}",slaveMongoProperties.getUri());
        return new MongoTemplate(
                new SimpleMongoClientDatabaseFactory(
                        MongoClients.create(slaveMongoProperties.getUri()),
                        slaveMongoProperties.getMongoClientDatabase()
                )
        );
    }

}
